﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MyAuthCore.Model.Beans;
using MyAuthCore.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyAuthCore.Api.Filters
{
    public class AuthFilter : Controller
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string token = string.Empty;
            token = context.HttpContext.Request.Headers["auth"];
            if(string.IsNullOrEmpty(token))
            {
                ResponseResult result = new ResponseResult();
                result.Code = StateCode.Error;
                result.Message = "无token值，请在http请求头加上auth=token";
                context.Result = new JsonResult(result);
                return;
            }
            string user= TokenHelper.GetNameByToken(token);
            var sesstion = context.HttpContext.Session.GetString(user);
            if (string.IsNullOrEmpty(sesstion) || sesstion!=token)
            {
                ResponseResult result = new ResponseResult();
                result.Code = StateCode.Error;
                result.Message = "Token无效";
                context.Result = new JsonResult(result);
                return;
            }
            base.OnActionExecuting(context);
        }
    }
}
